//
//  ViewController.swift
//  doubandiantai
//
//  Created by 王海申 on 2017/7/7.
//  Copyright © 2017年 王海申. All rights reserved.
//

import UIKit
import Alamofire
import AVFoundation
import ToastSwiftFramework
import SwiftyJSON

class MyViewController: UIViewController ,ChannelProtocol,UITableViewDelegate,UITableViewDataSource,HttpProtocol{

    @IBOutlet weak var bg: UIImageView!
    @IBOutlet weak var iim: UIImageView!
    @IBOutlet weak var orderButton: OrderButton!
    @IBOutlet weak var tl: UILabel!
    @IBOutlet weak var im: UIImageView!
    
    @IBOutlet weak var tv: UITableView!
    
    @IBOutlet weak var timerlabel: UILabel!
    
    var timer:Timer = Timer()
    var ehttp:HTTPController = HTTPController()
    
    var tableData:[JSON] = []
    
    @IBOutlet weak var payButton: EkoButton!
    var currentIndex:Int = 0
    
    
    @IBOutlet weak var progress: UIImageView!
    
    
    var channelData:[JSON] = []
    
    
    
    //申明媒体播放器
    var audioPlay:AVPlayer?
    var audioPlayItem:AVPlayerItem?
    
    //定义一个字典
    var imageCache = Dictionary<String,UIImage>()
    
    
    
    //播放
    
    func onSetAudion(url:String){
    
        
        
        
        
        print(url)
        let u = URL(string:url)
        
        self.audioPlayItem = AVPlayerItem(url: u!)
        
        
        self.audioPlay = AVPlayer(playerItem:self.audioPlayItem!)
        
        self.audioPlay?.play()
        
        
        timer.invalidate()
        timerlabel.text = "00:00"
        timer =
            
            Timer.scheduledTimer(timeInterval: 0.4, target: self, selector: #selector(MyViewController.onTimerUpdate), userInfo: nil, repeats: true)
        
    }
    
    
    func onTimerUpdate(){
        let c = audioPlay?.currentTime().seconds;
        
        if c! > 0.0{
            
            //let t = audioPlay?.currentTime().timescale
            //print(audioPlay?.aseet
            
            let t = audioPlayItem?.duration.seconds;
            
            let pro:CGFloat =  CGFloat(c! / t!)
            
            
            progress.frame.size.width = view.frame.size.width * pro;
            
            let all:Int = Int(c!)
            let m:Int = all % 60
            let f:Int = Int(all / 60)
            var hebing:String = ""
            if(f < 10){
                hebing = "0\(f)"
                
            }else{
                hebing = "\(f)"
            }
            if(m < 10){
                hebing += ":0\(m)"
                
            }else{
                hebing += ":\(m)"
            }
            timerlabel.text = hebing
            
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        
        //模糊背景
        
        
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
        let blurView = UIVisualEffectView(effect: blurEffect)
        
        
        blurView.frame.size = CGSize(width: bg.frame.width, height: bg.frame.height)
        
        bg.addSubview(blurView)
        
        
        
        im.layer.masksToBounds  = true
        im.layer.cornerRadius = im.frame.width / 2
        im.layer.borderColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.7).cgColor
        im.layer.borderWidth = 4
        
        iim.layer.masksToBounds = true
        iim.layer.cornerRadius = tl.frame.width / 2
        iim.layer.borderColor = UIColor(red: 1.0, green: 1.0, blue: 1.0, alpha: 0.7).cgColor
        iim.layer.borderWidth = 4
        
        
        let anim = CABasicAnimation(keyPath: "transform.rotation")
        // 设置动画属性
        anim.toValue = 2 * Double.pi
        anim.repeatCount = 10000
        anim.duration = 10
        // 将动画添加到图层上
        im.layer.add(anim, forKey: "")
        tv.delegate = self
        tv.dataSource = self;
        ehttp.delegate = self;
        
        
        
        
        ehttp.onSearch(url: "http://www.douban.com/j/app/radio/channels")
        ehttp.onSearch(url: "http://douban.fm/j/mine/playlist?type=n&channel=0&from=mainsite")
        
        tv.backgroundColor = UIColor.clear
        view.backgroundColor = UIColor.clear
        
        
        
        payButton.addTarget(self, action: #selector(MyViewController.onPlay), for: UIControlEvents.touchUpInside)
        
        
        orderButton.addTarget(self, action:#selector(self.order(btn:)), for: UIControlEvents.touchUpInside)
        
        
        
        NotificationCenter.default.addObserver(self, selector: Selector(("palyfinish")), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: audioPlay)
        
        
    }
    
    func playfinish(){
        
        switch(orderButton.order){
            
        case 1:
            currentIndex += 1
            if currentIndex > tableData.count {
                currentIndex = 0
            }
            onSelectRow(index: currentIndex)
        case 2:
            
            currentIndex = Int(arc4random()) % tableData.count
            
            onSelectRow(index: currentIndex)
        case 3:
            onSelectRow(index: currentIndex)
        default:
            "default"
        }

        
    }
    func onPlay(){
        
        if(payButton.isplay){
            audioPlay?.play()
        }else{
            audioPlay?.pause()
        }
        
    }
    func order(btn:OrderButton){
        
        var message:String = "";
        switch(btn.order){
            
        case 1:
            message = "循环播放"
        case 2:
            message =  "顺序播放"
        case 3:
            message = "单曲播放"
            
        default:
            message = "逗比"
        }
        
        var style = ToastStyle()
        
        // this is just one of many style options
        style.messageColor = .blue
        
        // present the toast with the new style
        self.view.makeToast(message, duration: 3.0, position: .bottom, style: style)
        
        
        
    }
    

    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
        return tableData.count;
    }
    
    
   
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
       let cell = tableView.dequeueReusableCell(withIdentifier: "song", for: indexPath)
        
        cell.backgroundColor = UIColor.clear
        cell.layer.borderColor = UIColor.clear.cgColor
        
        
        let rowData:JSON = tableData[indexPath.row]
        
        cell.textLabel?.text = rowData["title"].string
        cell.detailTextLabel?.text = rowData["artist"].string
        
        onGetCacheImage(url: rowData["picture"].string!,imageView: cell.imageView!);
        
        

       return cell;
    }
    

    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    func didReceiveResulets(resulets:AnyObject){
        
        let json = JSON(resulets)
        
        
        if let channels = json["channels"].array{
            self.channelData = channels
        }else if let song = json["song"].array{
            self.tableData = song
            
            self.tv.reloadData()
        }
    }
    
    
    func onGetCacheImage(url:String,imageView:UIImageView){
        
        let image = self.imageCache[url]
        if image == nil {
            
            
            Alamofire.request(url).responseData { response in
                
                
                if let data = response.result.value{
                    let img = UIImage(data:data)
                    
                    self.imageCache[url] = img;
                    imageView.image = img;
                }
            }
            
            
        }else{
            
            imageView.image = image;
        }
        
    }
    
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        let channelC:PindaoTableViewController = segue.destination as! PindaoTableViewController
        
        channelC.delegate = self;
        channelC.channelData = self.channelData;
        channelC.preController = self;
        
    }
    
    
    func onSelectRow(index:Int){
        let a  = IndexPath(row: index, section: 0)
    
        tv.selectRow(at: a, animated: false, scrollPosition:UITableViewScrollPosition.top)
        
        
        
        var rowData:JSON = self.tableData[index]
        let imageUrl =  rowData["picture"].string
        onSetImage(url: imageUrl!)
        
        onSetAudion(url: rowData["url"].string!)
    }
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    
        onSelectRow(index: indexPath.row)
        
    }
    
    func onSetImage(url:String){
        
        
        
        onGetCacheImage(url: url,imageView: self.im);
        
        
    }
    

    
    func onChangeChanel(channel_id:String){
        
        
        ehttp.onSearch(url: "http://douban.fm/j/mine/playlist?type=n&channel=\(channel_id)&from=mainsite")
        
        
        
    }
}

